package com.byq.mm.smartlib.obd.commands.decoder;

abstract public class CommandDecoder {
	byte sidrp;
	byte pid;
	protected byte[] response;
	public CommandDecoder(byte sidrp, byte pid) {
		super();
		this.sidrp = sidrp;
		this.pid = pid;
		response = new byte[responseLength()];
		response[0] = sidrp;
		response[1] = pid;
		
	}
	public void reset(){
		response = new byte[responseLength()];
		response[0] = sidrp;
		response[1] = pid;
	}
	public void setResponse(byte[] data){
		if(data.length != response.length)
			return;
		if(data[0] != response[0] ||data[1] != response[1] )
			return;
		for(int i = 0; i < response.length; i++)
			response[i] = data[i];
	
	}
	abstract protected int responseLength();
	public int eat(byte[] data, int startIndex){
		int l = responseLength();
		response = new byte[l];
		for(int i = 0; i < l; i++)
			response[i] = data[startIndex++];
		return l;
	}
	public double getA() {
		byte b = response[2];
		int v = b&0x0FF;
		return v;
	}
	public double getAB() {
		int v = (0x00ff&response[2])<<8|(0x00ff&response[3]);
		return v;
	}
	
	abstract public double getValue();
	abstract public double getMax();
	abstract public double getMin();
	abstract public String getUnit();
	abstract public String getName();
	abstract public String getGroup();
	public String getKey(){
		return "" + sidrp + pid;
	}
	
	public void simulate(){
		if(this.responseLength() == 3){
			
			int value =  (int) getA() + 3;
		
			value =  (value%256);
			value = value<<24;
			value = value /(256 * 256 * 256);
			response[2] = (byte) value;
		}
		if(this.responseLength() == 4){
			
			int value =  (int) getAB() + 256 * 3;
		
			int vh =  (value%(256 * 256));
			vh = vh&0xff00;
			int valueH = vh<<16;
			valueH = valueH /(256 * 256 * 256);
			response[2] = (byte) valueH;

			int valueL = value<<24;
			valueL = valueL /(256 * 256 * 256);
			response[3] = (byte) valueL;
			int v = (int) getAB();
			//assert(v == value);
		}
		
	}
}
